const Router = require('koa-router');
const router = new Router();
const tools = require("../../tools/tool");
const {db, QueryTypes} = require("../../models/db");
const pageParams = require("../../tools/cols");
router.post('/list/cmx', async ctx => {
    try {
        let body = ctx.request.body
        let user = ctx.user
        let search = body.search;
        let isExport = body.isExport;
        let searchTxt = search.searchTxt ? search.searchTxt : '';
        let tenantId = user.tenantId;
        let beginDate = search.beginDate ? search.beginDate : tools.getDay('', -15)
        let endDate = search.endDate ? search.endDate : tools.getDay()
        let buId = search.buId ? search.buId : 0;
        let salesId = search.salesId ? search.salesId : 0;
        let sql = `exec report_cus_bills_detail_all @tenantId=${tenantId},@beginDate='${beginDate}',@endDate='${endDate}',@buId=${buId},@salesId=${salesId}`;
        let list = await db.query(sql, {type: QueryTypes.SELECT})
        let retGp = tools.xe.groupBy(list, 'buId')
        let results = []
        for(let item in retGp) {
            let hasqc = false
            for (let i = 0; i < retGp[item].length; i++) {
                if(retGp[item][i].billType === '期初') {
                    hasqc = true
                    break
                }
            }
            if(retGp[item].length === 1 && hasqc && tools.xe.toNumber(retGp[item][0].ye) === 0) {
                continue
            }
            if(!hasqc) {
                results.push({
                    buId: retGp[item][0].buId,
                    buName: retGp[item][0].buName,
                    billType: '期初',
                    ye: ''
                })
            }
            retGp[item].map(row => {
                results.push(row)
            })
        }
        results.map(row => {
            if(tools.xe.toNumber(row.amount) == 0) {
                row.amount = ''
            }
            if(tools.xe.toNumber(row.hxAmount) == 0) {
                row.hxAmount = ''
            }
            if(tools.xe.toNumber(row.ysAdd) == 0) {
                row.ysAdd = ''
            }
            if(tools.xe.toNumber(row.ye) == 0) {
                row.ye = ''
            }
            row.ysAdd = tools.xe.toFixed(row.ye, 2)
            if(row.billType !=='期初') {
                row.ye = ''
                row.amount = tools.xe.toFixed(row.amount,2)
            }
            else {
                row.ysAdd = ''
            }
        })
        let lastRet = []
        for (let i = 0; i < results.length; i++) {
            lastRet.push(results[i])
            let row = {}
            row.buId = results[i].buId
            row.billType = '小计'
            row.hxAmount = ''
            row.buName = ''
            row.ye = ''
            // 要每个商户的最后一行加一行小计
            if(i+1 < results.length) {
                // 如果下一行是另一个商户了，加一行小计
                if(results[i+1].buId !== results[i].buId) {
                    lastRet.push(row)
                }
            }
            else {
                lastRet.push(row)
            }
        }
        let sub = 0
        for (let i = 0; i < lastRet.length - 1; i++) {
            if(lastRet[i+1].billType !== '期初' && lastRet[i+1].billType !== '小计') {
                let am = tools.xe.add(lastRet[i].ye, lastRet[i+1].ysAdd)
                lastRet[i+1].ye = am == 0 ?'': tools.xe.toFixed(am, 2)
                lastRet[i+1].buName = ''
            }
            if(lastRet[i].billType === '小计') {
                lastRet[i].ye = lastRet[i-1].ye==0?'':tools.xe.toFixed(lastRet[i-1].ye, 2)
            }
            if(lastRet[i].billType === '期初') {
                lastRet[i].ye = lastRet[i].ye == 0 ? '' : tools.xe.toFixed(lastRet[i].ye, 2)
                sub = 0
            }
            if(tools.xe.toNumber(lastRet[i].hxAmount) !== 0) {
                lastRet[i].hxAmount = tools.xe.toFixed(lastRet[i].hxAmount, 2)
            }
            sub = tools.xe.add(sub, lastRet[i].ysAdd)
            if(lastRet[i].billType === '小计') {
                lastRet[i].ysAdd = sub == 0 ?'':tools.xe.toFixed(sub, 2)
            }
        }
        if (isExport) {
            ctx.request.body.whichPage = '对账明细'
            let params = pageParams(ctx, tools)
            return await tools.doExcelOut(ctx, list, params)
        }
        else {
            return ctx.suc('', lastRet);
        }
    } catch (e) {
        return ctx.err('无返回数据')
    }
})

module.exports = router;